package my.myorm.tool.jdbc;

import java.util.Map;
import java.util.HashMap;
import java.sql.ResultSet;
import my.myorm.tool.orm.TableUtil;
import my.myorm.tool.orm.TableBeanMap;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2010-3-2
 * Time: 15:18:08
 * To change this template use File | Settings | File Templates.
 */
public abstract class ResultSetHandler {
    

    private String defaultTableName = "_default_table_name_";

  
    protected ResultList handleResult(ResultSet rs, boolean isAll) throws Exception {
    	return handleResult(rs, isAll, null);
    }
    
    /**
     * 
     * @param rs
     * @param isAll
     * @param tblName add by kinzhang ,union 
     * @return
     * @throws Exception
     */
    protected ResultList handleResult(ResultSet rs, boolean isAll, String unionTbl) throws Exception {
        ResultList results = new ResultList();
        
        //System.out.println("isAll:" + isAll);

        Map<String, String> tableMap = new HashMap<String, String>();
        Map<String, Map<String, String>> columnsMap = new HashMap<String, Map<String, String>>();
        columnsMap.put(defaultTableName, new HashMap<String, String>());

        ResultSetField[] fields = getResultSetFields(rs);
        
       // System.out.println("fields:" + fields);

        //表名和别名的映射,字段名和字段别名的映射
        if (fields != null) {
            for (int i = 0; i < fields.length; i++) {
                ResultSetField f = fields[i];
                String oriTableName = f.getOriginalTableName();
                
                String tableName = f.getTableName();
                String columnName = "";
                String label = f.getName();
                if (oriTableName == null || oriTableName.trim().equals("")) {//不属于任何表
                	
                    
                    //add by kinzhang 
                    //union 支持
                    if (unionTbl == null || unionTbl.equals("")) {
                    //	System.out.println("不属于任何表");
                        oriTableName = defaultTableName;
                        tableName = defaultTableName;
                        label = label.toLowerCase().trim();
                        columnName = "";
					}
                    else{
                    	oriTableName = unionTbl;
                        tableName = unionTbl;
                        label = label.toLowerCase().trim();
                        columnName = f.getFullOriginalName().substring(f.getFullOriginalName().lastIndexOf(".") + 1).trim();
                    }
                    
                } else {
                    oriTableName = oriTableName.trim().toLowerCase();
                    tableName = tableName.trim().toLowerCase();
                    label = label.trim().toLowerCase();
                    columnName = f.getFullOriginalName().substring(f.getFullOriginalName().lastIndexOf(".") + 1).trim();
                }
                tableMap.put(tableName, oriTableName);
               // System.out.println("tableMap:" + tableName + "->" + oriTableName);
                if (!columnsMap.containsKey(tableName)) {
                    columnsMap.put(tableName, new HashMap<String, String>());
                }
                if (unionTbl == null || unionTbl.equals("")) {
                	columnsMap.get(tableName).put(tableName + "." + label, columnName);
                }
                else{
                	columnsMap.get(tableName).put("." + label, columnName);
                }
                if (isAll) {
                    columnsMap.get(defaultTableName).put(tableName + "." + label, columnName);
                }
            }
        }
        String[] tablenames = tableMap.keySet().toArray(new String[0]);
        //System.out.println("tablenames.length:" + tablenames.length);
       // System.out.println("tablenames:" + java.util.Arrays.toString(tablenames));
      
        while (rs.next()) {
            RecordMap record = new RecordMap();
            for (int i = 0; i < tablenames.length; i++) {
                if (tablenames[i].equals(defaultTableName)) continue;
                String oriTableName = tableMap.get(tablenames[i]);                
                Map<String, String> columns = columnsMap.get(tablenames[i]);
                Class clazz = TableBeanMap.getBeanClass(TableUtil.getSummary(oriTableName));
                if (clazz != null) {//找到对应的bean
                    RowMapper mapper = TableBeanMap.getRowMapper(clazz);
                    Object obj = mapper.mapRow(rs, columns);
                    record.put(clazz, obj, tablenames[i]);
                } else {//找不到，则使用DefaultBean,将该table对应的hashmap加入到默认map中
                    columnsMap.get(defaultTableName).putAll(columns);
                }
            }
            DefaultBean defaultBean = new DefaultBean();
            defaultBean.mapRow(rs, columnsMap.get(defaultTableName));
            record.put(defaultBean.getClass(), defaultBean);
            results.add(record);
        }
        tableMap = null;
        columnsMap = null;
        fields = null;
        tablenames = null;
        return results;
    }

    protected abstract ResultSetField[] getResultSetFields(ResultSet rs) throws Exception;
}
